<?php

namespace app\admin\controller;

use app\common\controller\AdminController;
use app\common\model\GoodsCategory;
use app\common\model\GoodsSku;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="商品表")
 */
class Goods extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\common\model\Goods();

    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }

            list($page, $limit, $where) = $this->buildTableParames(['shop_name', 'price_low', 'price_high']);
//            if ($this->user['role'] == 1) {
//                $shopIds = \app\common\model\Shop::where('user_id', $this->user['id'])->column('id');
//                if ($shopIds) {
//                    $where[] = ['s.id', 'in', $shopIds];
//                }
//            }
            $filter = json_decode(input('filter'), true);
            if (isset($filter['shop_name'])) {
                if ($filter['shop_name'] == "平台") {
                    $where[] = ['g.shop_id', '=', 0];
                } else {
                    $where[] = ['s.name', 'like', '%' . $filter['shop_name'] . '%'];
                }
            }
            $price_low = 0;
            if (isset($filter['price_low'])) {
                $price_low = $filter['price_low'];
                $where[]   = ['g.price_high', '>=', $price_low];
            }
            if (isset($filter['price_high'])) {
                $price_high = $filter['price_high'];
                if ($price_high < $price_low) {
                    return json([
                        'code' => 1,
                        'msg'  => '价格最大值不能小于价格最小值',
                    ]);
                }
                $where[] = ['g.price_low', '<=', $price_high];
            }

            try {
                $count = $this->model->alias('g')
                    ->leftJoin('shop s', 's.id=g.shop_id')
                    ->leftJoin('pm_goods_category gc', 'g.category_id = gc.id')
                    ->where($where)
                    ->count();
                $list  = $this->model->alias('g')
                    ->leftJoin('shop s', 's.id=g.shop_id')
                    ->leftJoin('pm_goods_category gc', 'g.category_id = gc.id')
                    ->field('g.*,s.name as shop_name,gc.name as category_name')
                    ->where($where)
                    ->page($page, $limit)
                    ->order('category_id', 'desc')
                    ->order($this->sort)
                    ->select();
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage() . $e->getTraceAsString());
//                dd($e->getMessage());
            }

            foreach ($list as $k => $l) {
                if ($l['shop_id'] == 0) {
                    $list[$k]['shop_name'] = '平台';
                }
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [
                'name|商品名称'        => 'require',
                'img|商品主图'         => 'require',
                'category_id|商品分类' => 'require',
                //'specs|商品规格' => 'require|array',
            ];
            $this->validate($post, $rule);
            Db::startTrans();
            try {
                $post['is_spec'] = $specType = input('spec_type', 0, 'intval');
                $post['status']  = 1;
                if ($specType == 0) {//单规格
                    if (!is_numeric($post['original_price'])) {
                        throw new \Exception('商品原价不是数字');
                    }
                    if (!is_numeric($post['price'])) {
                        throw new \Exception('商品现价不是数字');
                    }
                    $post['sku_json'] = json_encode([['name' => '默认', 'value' => ['默认']]], JSON_UNESCAPED_UNICODE);

                    $post['price_low']   = $post['price'];
                    $post['price_high']  = $post['price'];
                    $post['total_stock'] = $post['stock'];
                    $goods               = \app\common\model\Goods::create($post);
                    $skuData             = [
                        'goods_id'       => $goods->id,
                        // 'sku_code' => $post['specs']['sku_code'][0],
                        'original_price' => $post['original_price'],
                        'price'          => $post['price'],
                        'stock'          => $post['stock'],
                        'img'            => $post['img'],
                        'sku_json'       => json_encode([['name' => '默认', 'value' => '默认']], JSON_UNESCAPED_UNICODE)
                    ];

                    GoodsSku::create($skuData);
                } else {
                    //多规格
                    $specAll    = input('specs_all');
                    $specAllArr = json_decode($specAll, true);
                    if (empty($specAllArr)) {
                        throw new \Exception('商品规格错误');
                    }
                    $len          = 0;
                    $specNamesArr = [];
                    $specsArr     = [];
                    //
                    $post['price_low']   = 0;
                    $post['price_high']  = 0;
                    $post['total_stock'] = 0;
                    foreach ($specAllArr as $s) {
                        if (!$s['name']) {
                            throw new \Exception('商品规格错误');
                        }
                        $specNamesArr[] = $s['name'];
                        if (empty($s['value'])) {
                            throw new \Exception($s['name'] . '规格错误');
                        }
                        $specsArr[] = $s['value'];

                    }
                    $post['sku_json'] = $specAll;
                    $goods            = \app\common\model\Goods::create($post);
                    $discart          = Cartesian($specsArr);

                    $skuInsertData = [];

                    foreach ($discart as $k => $d) {
                        if (!is_numeric($post['specs']['original_price'][$k])) {
                            throw new \Exception(implode('', $d) . '原价错误');
                        }
                        if (!is_numeric($post['specs']['price'][$k])) {
                            throw new \Exception(implode('', $d) . '现价错误');
                        }
                        if (!is_numeric($post['specs']['stock'][$k])) {
                            throw new \Exception(implode('', $d) . '库存错误');
                        }
                        if (!$post['specs']['img'][$k]) {
                            //  throw new \Exception(implode('', $d) . '图片错误');
                        }
                        $s = [];
                        foreach ($d as $kk => $dd) {
                            $s[] = [
                                'name'  => $specAllArr[$kk]['name'],
                                'value' => $dd
                            ];
                        }
                        if ($post['price_low'] == 0) {
                            $post['price_low'] = $post['specs']['price'][$k];
                        }
                        if ($post['price_low'] > $post['specs']['price'][$k]) {
                            $post['price_low'] = $post['specs']['price'][$k];
                        }
                        if ($post['price_high'] == 0) {
                            $post['price_high'] = $post['specs']['price'][$k];
                        }
                        if ($post['price_high'] < $post['specs']['price'][$k]) {
                            $post['price_high'] = $post['specs']['price'][$k];
                        }
                        $post['total_stock'] += $post['specs']['stock'][$k];
                        $skuInsertData       = [
                            'goods_id'       => $goods->id,
                            'sku_code'       => $post['specs']['sku_code'][$k],
                            'original_price' => $post['specs']['original_price'][$k],
                            'price'          => $post['specs']['price'][$k],
                            'stock'          => $post['specs']['stock'][$k],
                            'img'            => $post['specs']['img'][$k],
                            'sku_json'       => json_encode($s, JSON_UNESCAPED_UNICODE)
                        ];
                        GoodsSku::create($skuInsertData);
                    }
                    $goods->price_low   = $post['price_low'];
                    $goods->price_high  = $post['price_high'];
                    $goods->total_stock = $post['total_stock'];
                    $goods->save();

                }
                Db::commit();
                // $save = $this->model->save($post);
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('保存失败:' . $e->getMessage() . $e->getTraceAsString());
            }
            $this->success('保存成功');
        }

        $shops = [];
        $cates = [];
//        if ($this->user['role'] == 1) {
//            $this->assign('is_shop', 1);
//            $shops = \app\common\model\Shop::where('user_id', $this->user['id'])->where('status', 1)->field('id,name')->select()->toArray();
//            $cates = GoodsCategory::whereIn('shop_id', array_column($shops, 'id'))->order('sort desc,id desc')->select()->toArray();
//        } else {
        $this->assign('is_shop', 0);
        $cates = GoodsCategory::where('shop_id', 0)->order('sort desc,id desc')->select()->toArray();
//        }
        $newCate      = [];
        $repeatString = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
        foreach ($cates as $k => $v) {
            if ($v['pid'] == 0) {
                $newCate[] = $v;
            }
            foreach ($cates as $kk => $vv) {
                if ($vv['pid'] != 0 && $vv['pid'] == $v['id']) {
                    $vv['name'] = "{$repeatString}├{$repeatString}" . $vv['name'];
                    $newCate[]  = $vv;
                }
            }
        }
        $this->assign('shops', $shops);
        $this->assign('cates', $newCate);

        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [
                'name|商品名称'        => 'require',
                'img|商品主图'         => 'require',
//                'category_id|商品分类' => 'require',
                //'specs|商品规格' => 'require|array',
            ];
            $this->validate($post, $rule);
            Db::startTrans();
            try {
                GoodsSku::where('goods_id', $id)->useSoftDelete('delete_time', time())->delete();
                $post['is_spec'] = $specType = input('spec_type', 0, 'intval');
                $post['status']  = 1;
                if ($specType == 0) {//单规格
                    if (!is_numeric($post['original_price'])) {
                        throw new \Exception('商品原价不是数字');
                    }
                    if (!is_numeric($post['price'])) {
                        throw new \Exception('商品现价不是数字');
                    }
                    $post['sku_json'] = json_encode([['name' => '默认', 'value' => ['默认']]], JSON_UNESCAPED_UNICODE);
                    $post['price_low']   = $post['price'];
                    $post['price_high']  = $post['price'];
                    $post['total_stock'] = $post['stock'];
                    $goods   = \app\common\model\Goods::update($post, ['id' => $id]);
                    $skuData = [
                        'goods_id'       => $id,
                        // 'sku_code' => $post['specs']['sku_code'][0],
                        'original_price' => $post['original_price'],
                        'price'          => $post['price'],
                        'stock'          => $post['stock'],
                        'img'            => $post['img'],
                        'sku_json'       => json_encode([['name' => '默认', 'value' => '默认']], JSON_UNESCAPED_UNICODE)
                    ];

                    GoodsSku::create($skuData);
                } else {
                    //多规格
                    $specAll    = input('specs_all');
                    $specAllArr = json_decode($specAll, true);
                    if (empty($specAllArr)) {
                        throw new \Exception('商品规格错误');
                    }
                    $len          = 0;
                    $specNamesArr = [];
                    $specsArr     = [];
                    //
                    $post['price_low']   = 0;
                    $post['price_high']  = 0;
                    $post['total_stock'] = 0;

                    foreach ($specAllArr as $s) {
                        if (!$s['name']) {
                            throw new \Exception('商品规格错误');
                        }
                        $specNamesArr[] = $s['name'];
                        if (empty($s['value'])) {
                            throw new \Exception($s['name'] . '规格错误');
                        }
                        $specsArr[] = $s['value'];
                    }
                    $post['sku_json'] = $specAll;
                    $goods            = \app\common\model\Goods::update($post, ['id' => $id]);
                    $discart          = Cartesian($specsArr);

                    //$skuInsertData = [];

                    foreach ($discart as $k => $d) {
                        if (!is_numeric($post['specs']['original_price'][$k])) {
                            throw new \Exception(implode('', $d) . '原价错误');
                        }
                        if (!is_numeric($post['specs']['price'][$k])) {
                            throw new \Exception(implode('', $d) . '现价错误');
                        }
                        if (!is_numeric($post['specs']['stock'][$k])) {
                            throw new \Exception(implode('', $d) . '库存错误');
                        }
                        if (!$post['specs']['img'][$k]) {
                            //  throw new \Exception(implode('', $d) . '图片错误');
                        }
                        $s = [];
                        foreach ($d as $kk => $dd) {
                            $s[] = [
                                'name'  => $specAllArr[$kk]['name'],
                                'value' => $dd
                            ];
                        }
                        if ($post['price_low'] == 0) {
                            $post['price_low'] = $post['specs']['price'][$k];
                        }
                        if ($post['price_low'] > $post['specs']['price'][$k]) {
                            $post['price_low'] = $post['specs']['price'][$k];
                        }
                        if ($post['price_high'] == 0) {
                            $post['price_high'] = $post['specs']['price'][$k];
                        }
                        if ($post['price_high'] < $post['specs']['price'][$k]) {
                            $post['price_high'] = $post['specs']['price'][$k];
                        }
                        $post['total_stock'] += $post['specs']['stock'][$k];
                        $skuInsertData = [
                            'goods_id'       => $id,
                            'sku_code'       => $post['specs']['sku_code'][$k],
                            'original_price' => $post['specs']['original_price'][$k],
                            'price'          => $post['specs']['price'][$k],
                            'stock'          => $post['specs']['stock'][$k],
                            'img'            => $post['specs']['img'][$k],
                            'sku_json'       => json_encode($s, JSON_UNESCAPED_UNICODE)
                        ];
                        GoodsSku::create($skuInsertData);
                    }
                    $goods->price_low   = $post['price_low'];
                    $goods->price_high  = $post['price_high'];
                    $goods->total_stock = $post['total_stock'];
                    $goods->save();

                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('保存失败' . $e->getMessage());
            }
            $this->success('保存成功');
        }

        if ($row['is_spec'] == 0) {
            $row['specs'] = GoodsSku::where('goods_id', $id)->find();
        } else {
            $row['specs'] = json_encode(GoodsSku::where('goods_id', $id)->field('sku_code,original_price,price,img,stock')->select()->toArray(), JSON_UNESCAPED_UNICODE);
        }
        //var_dump($row->getData());
        $this->assign('row', $row->getData());
        $shops = [];
        $cates = [];
        if ($this->user['role'] == 1) {
            $this->assign('is_shop', 1);
            $shops = \app\common\model\Shop::where('user_id', $this->user['id'])->where('status', 1)->field('id,name')->select()->toArray();
            $cates = GoodsCategory::whereIn('shop_id', array_column($shops, 'id'))->order('sort desc,id desc')->select()->toArray();
        } else {
            $this->assign('is_shop', 0);
            $cates = GoodsCategory::where('shop_id', 0)->order('sort desc,id desc')->select()->toArray();
        }

        $this->assign('shops', $shops);
        $this->assign('cates', $cates);
        return $this->fetch();
    }

    public function list()
    {
        $page     = input('page', 1, 'intval');
        $pageSize = input('page_size', 15, 'intval');
        $keyword  = input('keyword', '', 'trim');
        $selected = input('selected', '', 'trim');
        $exclude  = input('exclude', '', 'trim');
        $cate_id  = input('cate_id', '', 'trim');
        $where    = [];
//        $where[] = ['shop_id','=',0];
        if ($keyword) {
            $where[] = ['title', 'like', "%$keyword%"];
        }
        if ($exclude) {
            $where[] = ['id', 'not in', explode(',', $exclude)];
        }
        if ($cate_id) {
            $where[] = ['category_id', '=', $cate_id];
        }
        $list       = \app\common\model\Goods::where($where)->field('name,id as value');
        $totalCount = $list->count();
        $totalPage  = ceil($totalCount / $pageSize);

        if ($selected) {
            $list = $list->orderRaw('field(id,' . $selected . ') desc');
        }
        $list = $list->order('id desc')->page($page, $pageSize)->select()->toArray();
        foreach ($list as $k => $l) {
            if (in_array($l['value'], explode(',', $selected))) {
                $list[$k]['selected'] = true;
            }
        }
        return $this->success('', ['list' => $list, 'total_page' => $totalPage]);
    }

    /**
     * 获取商品多规格下面的详细库存
     */
    public function stockList()
    {
        $id   = input('id');
        $list = GoodsSku::where('goods_id', $id)->field('')->select();
        return json(['code' => 0, 'msg' => '获取成功', 'data' => $list]);
    }
}